<!--
  文件用途：评论管理页（仅注释，不改逻辑）
  功能：
  - 按模式筛选评论（schedule/worklog/all）
  - 支持删除评论与分页浏览
  - 集成敏感词工具：支持在线刷新与本地临时添加敏感词
-->
<template>
  <div class="admin-page">
    <div class="page-header">
      <h1 class="page-title">评论管理</h1>
      <p class="page-subtitle">管理系统中的所有评论</p>
    </div>
    
    <el-card class="content-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="card-title">评论列表</span>
          <div class="header-actions">
            <el-select v-model="mode" style="width:140px">
              <el-option label="按日程" value="schedule" />
              <el-option label="按日志" value="worklog" />
              <el-option label="全部(管理员)" value="all" />
            </el-select>
            <el-input v-if="mode!=='all'" v-model="sid" :placeholder="mode==='schedule' ? 'Schedule ID' : 'Worklog ID'" style="width: 200px; margin-left: 8px" />
            <el-button type="primary" @click="load" style="margin-left: 8px">加载</el-button>
          </div>
        </div>
      </template>
      <div style="margin-bottom:12px">
        <el-tag>临时添加敏感词：</el-tag>
        <el-input v-model="sensitiveInput" placeholder="用逗号分隔，如：敏感1,敏感2" style="width:300px; margin-left: 8px" />
        <el-button type="primary" size="small" @click="updateSensitiveWords" style="margin-left: 8px">添加</el-button>
        <el-button type="info" size="small" @click="loadSensitiveWords" style="margin-left: 8px">刷新敏感词</el-button>
      </div>
    <el-table :data="pagedList" v-loading="loading" size="small">
      <el-table-column prop="commentId" label="ID" width="70" />
      <el-table-column label="用户" width="120">
        <template #default="{ row }">{{ getUserName(row.creatorId) }}</template>
      </el-table-column>
      <el-table-column label="内容">
        <template #default="{ row }">
          <div>
            <el-tag v-if="checkCommentSensitive(row.content)" type="warning" size="small" style="margin-right: 8px">含敏感词</el-tag>
            <span>{{ row.content }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="时间" width="180">
         <template #default="{ row }">
           {{ formatDateTime(row.createTime) }}
         </template>
       </el-table-column>
      <el-table-column prop="relatedType" label="类型" width="90" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-popconfirm
            title="确定要删除这条评论吗？删除后将无法恢复！"
            @confirm="deleteComment(row.commentId)"
          >
            <template #reference>
              <el-button
                type="danger"
                size="small"
                :loading="deleting === row.commentId"
                :disabled="deleting !== null"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:12px; display:flex; justify-content:flex-end">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="list.length"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10,20,50,100]"
      />
    </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { api } from '@/utils/api'
import { ElMessage } from 'element-plus'
import { filterSensitiveWords, sensitiveWords, loadSensitiveWords, containsSensitiveWords, findSensitiveWords } from '@/utils/sensitive'

const sid = ref('')
const list = ref([])
const loading = ref(false)
const mode = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const pagedList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return list.value.slice(start, start + pageSize.value)
})

// 删除评论相关
const deleting = ref(null)

// 用户映射
const userMap = ref(new Map())

// 敏感词相关
const sensitiveInput = ref('')

// 更新本地敏感词（临时添加）
function updateSensitiveWords() {
  const localWords = sensitiveInput.value.split(',').map(w => w.trim()).filter(Boolean)
  localWords.forEach(word => {
    if (word && !sensitiveWords.value.some(w => w.word === word)) {
      sensitiveWords.value.push({
        word: word,
        replacement: '***',
        action: 'replace',
        status: 'active'
      })
    }
  })
  ElMessage.success('临时敏感词已添加')
}

// 删除评论
async function deleteComment(commentId) {
  if (!commentId) {
    ElMessage.error('评论ID无效')
    return
  }
  
  try {
    deleting.value = commentId
    await api.del(`/comment/delete/${commentId}`)
    ElMessage.success('删除成功')
    // 重新加载评论列表
    await load()
  } catch (error) {
    console.error('删除评论失败:', error)
    ElMessage.error('删除失败：' + error.message)
  } finally {
    deleting.value = null
  }
}

// 检查评论是否包含敏感词
function checkCommentSensitive(content) {
  return containsSensitiveWords(content)
}

// 高亮敏感词（管理员页面显示原始敏感词并标记）
function highlightSensitiveWords(content) {
  if (!content) {
    return content
  }
  
  // 如果没有敏感词列表，尝试重新加载
  if (!sensitiveWords.value || sensitiveWords.value.length === 0) {
    console.log('敏感词列表为空，尝试重新加载')
    loadSensitiveWords()
    return content
  }
  
  let result = content
  let hasMatch = false
  
  // 使用从后端获取的敏感词列表进行高亮
  sensitiveWords.value.forEach(wordObj => {
    if (wordObj && wordObj.word && wordObj.status === 'active') {
      const word = wordObj.word
      console.log('检查敏感词:', word, '在内容中:', content)
      
      // 创建正则表达式，转义特殊字符
      const regex = new RegExp(word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi')
      const matches = content.match(regex)
      
      if (matches) {
        console.log('找到匹配:', matches)
        hasMatch = true
        // 保持原始敏感词内容，只添加红色高亮样式
        result = result.replace(regex, (match) => {
          return `<span style="background-color: #ffcccc; color: #d32f2f; padding: 2px 4px; border-radius: 3px; font-weight: bold;">${match}</span>`
        })
      }
    }
  })
  
  console.log('高亮结果:', result, '是否有匹配:', hasMatch)
  return result
}

// 格式化时间显示
function formatDateTime(dateTime) {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  if (isNaN(date.getTime())) return dateTime
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取用户信息
async function loadUserInfo(userIds) {
  if (!userIds || userIds.length === 0) return
  
  try {
    // 过滤掉已经获取过的用户ID
    const newUserIds = userIds.filter(id => !userMap.value.has(id))
    if (newUserIds.length === 0) return
    
    // 批量获取用户信息 - 使用分页方式获取所有用户然后过滤
  const usersResp = await api.get('/user/list', { page: 1, size: 1000 })
  const allUsers = Array.isArray(usersResp) ? usersResp : (usersResp.records || [])
    // 过滤出需要的用户
    const userList = allUsers.filter(user => newUserIds.includes(user.userId))
    
    // 更新用户映射
    userList.forEach(user => {
      if (user.userId) {
        userMap.value.set(user.userId, {
          username: user.username,
          nickname: user.nickname
        })
      }
    })
  } catch (e) {
    console.warn('获取用户信息失败:', e)
  }
}

// 根据用户ID获取用户名
function getUserName(creatorId) {
  if (!creatorId) return '-'
  const user = userMap.value.get(creatorId)
  return user ? (user.username || user.nickname || creatorId) : creatorId
}

async function load() {
  if (mode.value !== 'all' && !sid.value) {
    ElMessage.warning('请输入ID')
    return
  }
  loading.value = true
  try {
    const path = mode.value === 'all'
      ? '/comment/list/all'
      : (mode.value === 'schedule' ? `/comment/list/schedule/${sid.value}` : `/comment/list/worklog/${sid.value}`)
    
    list.value = await api.get(path)
    if (!Array.isArray(list.value)) list.value = []
    
    // 获取所有评论的创建者ID
    const creatorIds = [...new Set(list.value.map(item => item.creatorId).filter(Boolean))]
    await loadUserInfo(creatorIds)
    
    currentPage.value = 1
  } catch (e) {
    const msg = String(e && e.message || '')
    if (msg.startsWith('403')) {
      ElMessage.error('需要管理员权限，请使用管理员账号登录')
    } else {
      ElMessage.error('加载失败: ' + (e.message || ''))
    }
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await loadSensitiveWords()
  await load()
})

watch(mode, (val) => {
  if (val === 'all') {
    load()
  }
})
</script>

<style scoped>
.admin-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.content-card {
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}
</style>
